package com.huike.contract.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huike.business.domain.TbBusiness;
import com.huike.business.mapper.TbBusinessMapper;
import com.huike.clues.domain.SysUser;
import com.huike.clues.domain.TbActivity;
import com.huike.clues.domain.TbCourse;
import com.huike.clues.mapper.SysUserMapper;
import com.huike.clues.mapper.TbActivityMapper;
import com.huike.clues.mapper.TbCourseMapper;
import com.huike.common.core.page.TableDataInfo;
import com.huike.common.utils.SecurityUtils;
import com.huike.common.utils.bean.BeanUtils;
import com.huike.contract.domain.TbContract;
import com.huike.contract.domain.dto.ContactPageQueryDTO;
import com.huike.contract.domain.dto.TbContractDTO;
import com.huike.contract.domain.vo.TbContractVo;
import com.huike.contract.service.TbContractService;
import com.huike.contract.mapper.TbContractMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.*;

/**
 * @author 93238
 * @description 针对表【tb_contract(合同)】的数据库操作Service实现
 * @createDate 2023-10-12 06:42:55
 */
@AllArgsConstructor
@Service
@Slf4j
public class TbContractServiceImpl extends ServiceImpl<TbContractMapper, TbContract>
        implements TbContractService {


    private TbBusinessMapper tbBusinessMapper;
    private SysUserMapper sysUserMapper;
    private TbCourseMapper tbCourseMapper;
    private TbActivityMapper tbActivityMapper;
    private TbContractMapper tbContractMapper;

    /**
     * 新增合同
     *
     * @param tbContractDTO
     */
    @Override
    public void addContracr(TbContractDTO tbContractDTO) {
        TbContract tbContract = new TbContract();
        Long userId = SecurityUtils.getUserId();
        SysUser user = sysUserMapper.selectById(userId);
        TbActivity tbActivity = tbActivityMapper.selectById(tbContract.getId());
        TbCourse tbCourse = tbCourseMapper.selectById(tbContract.getCourseId());
        TbBusiness tbBusiness = tbBusinessMapper.selectOne(new QueryWrapper<TbBusiness>().eq("phone", tbContractDTO.getPhone()));
        Map map = contractOrder(tbActivity, tbCourse);

        BeanUtils.copyBeanProp(tbContract, tbContractDTO);
        tbContract.setActivityName(tbActivity.getName());
        tbContract.setCourseName(tbCourse.getName());
        tbContract.setStatus(TbContract.ContractStatusType.FINISH.getValue());
        tbContract.setCreateBy(user.getUserName());
        tbContract.setDeptId(user.getDeptId());
        tbContract.setCreateTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
        tbContract.setContractOrder((Double) map.get(1));
        tbContract.setDiscountType((String) map.get(0));
        tbContract.setCoursePrice(tbCourse.getPrice() * 1.0);
        tbContract.setBusinessId(tbBusiness.getId());
        tbContractMapper.insert(tbContract);
    }

    /**
     * 获取订单价格 + 折扣类型
     *
     * @param tbActivity
     * @param tbCourse
     * @return
     */
    private Map contractOrder(TbActivity tbActivity, TbCourse tbCourse) {
        Map map = new HashMap();
        Integer type = null;
        Double contractOrder = tbCourse.getPrice() * 1.0;
        Double discount = tbActivity.getDiscount();
        Integer vouchers = tbActivity.getVouchers();
        if (discount != null) {
            contractOrder = contractOrder * discount;
            type = 1;
        }
        if (vouchers != null) {
            contractOrder = contractOrder - vouchers;
            type = 2;
        }
        String discountType = null;
        if (type != null) {
            discountType = tbContractMapper.selectDiscountTypeByType(type,"dict_type");

        }
        map.put(0, discountType);
        map.put(1, contractOrder);

        return map;
    }

    /**
     * 查询合同列表
     *
     * @param contactPageQueryDTO
     * @return
     */
    @Override
    public TableDataInfo<List<TbContract>> pageContract(ContactPageQueryDTO contactPageQueryDTO) {
        Page<TbContract> page = new Page<>(contactPageQueryDTO.getPageNum(), contactPageQueryDTO.getPageSize());

        LambdaQueryWrapper<TbContract> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        if (contactPageQueryDTO.getParams().get("beginCreateTime") != null && !(contactPageQueryDTO.getParams().get("beginCreateTime").equals(""))
                && contactPageQueryDTO.getParams().get("endCreateTime") != null && !(contactPageQueryDTO.getParams().get("endCreateTime").equals("")))
        {
            String beginCreateTime = (String) contactPageQueryDTO.getParams().get("beginCreateTime");
            LocalDateTime beginCreateDateTime = LocalDateTime.of(LocalDate.parse(beginCreateTime), LocalTime.MIN);
            String endCreateTime = (String) contactPageQueryDTO.getParams().get("endCreateTime");
            LocalDateTime endCreateDateTime = LocalDateTime.of( LocalDate.parse(endCreateTime) , LocalTime.MAX);
            lambdaQueryWrapper.ge(TbContract::getCreateTime, beginCreateDateTime);
            lambdaQueryWrapper.le(TbContract::getCreateTime, endCreateDateTime);
        }

        lambdaQueryWrapper.like(contactPageQueryDTO.getContractNo()!=null, TbContract::getContractNo, contactPageQueryDTO.getContractNo());
        lambdaQueryWrapper.like(contactPageQueryDTO.getName()!=null, TbContract::getName, contactPageQueryDTO.getName());
        lambdaQueryWrapper.like(contactPageQueryDTO.getPhone()!=null, TbContract::getPhone, contactPageQueryDTO.getPhone());
        lambdaQueryWrapper.eq(contactPageQueryDTO.getSubject()!=null, TbContract::getSubject, contactPageQueryDTO.getSubject());
        lambdaQueryWrapper.eq(contactPageQueryDTO.getCourseId()!=null, TbContract::getCourseId, contactPageQueryDTO.getCourseId());

        tbContractMapper.selectPage(page, lambdaQueryWrapper);

        TableDataInfo<List<TbContract>> tableDataInfo = new TableDataInfo<>();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(page.getRecords());

        return tableDataInfo;
    }

    /**
     * 获取总和
     * @hgb
     * @return {@link Double}
     */
    @Override
    public Double getSum(String starTime , String endTime) {
        Double sum = tbContractMapper.getSum(starTime , endTime);
        return sum;
    }

    /**
     * 根据id查询合同详情
     *
     * @param id
     * @return
     */
    @Override
    public TbContractVo findById(Long id) {
        TbContract tbContract = tbContractMapper.selectById(id);
        TbContractVo tbContractVo = new TbContractVo();
        tbContractVo.setOrder(tbContract.getContractOrder());
        BeanUtils.copyBeanProp(tbContractVo, tbContract);
        return tbContractVo;
    }

    /**
     * 修改合同
     *
     * @param tbContractDTO
     */
    @Override
    public void updateContract(TbContractDTO tbContractDTO) {
        TbContract tbContract = new TbContract();
        BeanUtils.copyBeanProp(tbContract, tbContractDTO);
        tbContractMapper.updateById(tbContract);
    }

    /**
     * 商机转化为合同
     * @param id
     * @param tbcontractDTO
     */
    @Override
    public void changeToContract(Long id, TbContractDTO tbcontractDTO) {
        TbBusiness tbBusiness = tbBusinessMapper.selectById(id);
        TbActivity tbActivity = tbActivityMapper.selectById(tbBusiness.getActivityId());
        TbCourse tbCourse = tbCourseMapper.selectById(tbBusiness.getCourseId());
        TbContract tbContract = new TbContract();
        Map map = contractOrder(tbActivity, tbCourse);

        BeanUtils.copyBeanProp(tbContract, tbcontractDTO);
        tbContract.setName(tbBusiness.getName());
        tbContract.setSubject(tbBusiness.getSubject());
        tbContract.setActivityId(tbBusiness.getActivityId());
        tbContract.setActivityName(tbActivity.getName());
        tbContract.setCourseId(tbBusiness.getCourseId());
        tbContract.setCourseName(tbCourse.getName());
        tbContract.setChannel(tbBusiness.getChannel());
        tbContract.setStatus(TbContract.ContractStatusType.FINISH.getValue());
        tbContract.setCreateBy(SecurityUtils.getUsername());
        tbContract.setDeptId(SecurityUtils.getDeptId());
        tbContract.setCreateTime(Date.from(LocalDateTime.now().atZone(ZoneId.systemDefault()).toInstant()));
        tbContract.setContractOrder((Double) map.get(1));
        tbContract.setDiscountType((String) map.get(0));
        tbContract.setCoursePrice(tbCourse.getPrice() * 1.0);
        tbContract.setBusinessId(tbBusiness.getId());
        tbContractMapper.insert(tbContract);
    }
}




